<?php

namespace App\Models\Oauth;

use Illuminate\Support\Facades\DB;
use App\Models\Model;
use App\Models\Oauth\UserTypeModel;

/**
 * 用户和用户类型关联模型
 */
class UserTypeMapModel extends Model
{

    const TABLENAME = 'tw_base_user_type_map';

    /**
     * 初始化并返回数据库请求构建器
     *
     * @return Illuminate\Support\Facades\DB::table(TABLENAME)
     */
    public static function dbTable()
    {
        return DB::table(self::TABLENAME);
    }

    /**
     * 获取用户类型
     */
    public static function getUserType($where)
    {
        return self::dbTable()->select(array('id', 'user_id', 'type_id'))->where($where)->get();
    }

    /**
     * 添加用户类型关联
     */
    public static function addUserType($userId, $typeId)
    {
        $data['user_id'] = $userId;
        $data['type_id'] = $typeId;
        $data['created'] = time();
        return self::dbTable()->insert($data);
    }

    /**
     * 删除用户类型
     */
    public static function delUserType($where)
    {
        return self::dbTable()->where($where)->delete();
    }

    public static function getUserTypeName($userId)
    {
        $query = DB::table(self::TABLENAME . ' as t');
        return $query->select(DB::raw('t.type_id,n.name'))
            ->leftJoin(UserTypeModel::TABLENAME.' as n','n.id','=','t.type_id')
            ->where('t.user_id', $userId)
            ->get();
    }
}

?>